import React, { Component } from 'react'
import {
  View, Text, StyleSheet, KeyboardAvoidingView, Platform,
  ScrollView, TouchableOpacity, Image
} from 'react-native'
import Picker from 'react-native-picker'
import ActionSheet from 'react-native-actionsheet'
import NavBar from 'src/components/navBar'
import Divider from 'src/components/Divider'
import navigationhelper from 'src/components/navigationhelper'
import NameInput, { InputTypes } from 'src/components/Input/NameInput'
import { inject } from 'mobx-react/native'
import { isIPhoneX, getPovinceAndCityName, getPovinceAndCityId } from 'src/util'
import Layer from 'src/components/Layer'

@inject('cardManager', 'userAuth')
export default class AddCardView extends Component {

  constructor(props) {
    super(props)
    const data = this.props.navigation.getParam('data')
    console.log('data==', data)

    var channel = data.plan.channel
    var repaymentChannel = ''
    data.channel.forEach(function (item) {
      if (item.id == channel) {
        repaymentChannel = item.show_name
      }
    })


    var method = data.plan.daily_repayment_times
    var repaymentMethod = ''
    data.repayment_type.forEach(function (item) {
      if (item.value == method) {
        repaymentMethod = item.name
      }
    })
    var repaymentDate = ''
    data.plan.date_list.forEach(function (item) {
      repaymentDate = repaymentDate + item + ','
    })
    this.mounted = false
    let area = getPovinceAndCityName(props.cardManager.areaData, [data.plan.province, data.plan.city])
    this.state = {
      data: data,
      repaymentDate: repaymentDate,
      area: area,
      repaymentMethod: repaymentMethod,
      repaymentChannel: repaymentChannel
    }
  }

  componentDidMount() {
    if (this.props.cardManager.areaPureData.length === 0) {
      this.props.cardManager.fetchArea().then(() => {
        let area = getPovinceAndCityName(this.props.cardManager.areaData, [this.state.data.plan.province, this.state.data.plan.city])
        this.setState({
          area: area
        })
      })
    }
    this.mounted = true
  }

  componentWillUnmount() {
    this.mounted = false
  }

  handleShowDatePicker = () => {
    let __this = this;
    this.props.navigation.navigate('TestCalendar', {
      data: this.state.data,
      callback: ((selectdDay) => {
        console.log(selectdDay);
        if (selectdDay.length > 0) {
          var repaymentDate = '';
          selectdDay.forEach(function (item) {
            repaymentDate = repaymentDate + item + ','
          })
          __this.onUpdatePlan({
            plan_day: selectdDay
          })
          __this.setState({
            repaymentDate: repaymentDate
          });
        }
      })
    });
  }

  handleShowAreaPicker = () => {
    let payload = {
      pickerData: this.props.cardManager.areaPureData,
      selectedValue: this.state.area,
      pickerTitleText: '选择省市',
      pickerCancelBtnText: '取消',
      pickerConfirmBtnText: '确定',
      onPickerConfirm: data => {
        this.setState({ area: data })
        let areaIds = getPovinceAndCityId(this.props.cardManager.areaData, data)
        this.onUpdatePlan({
          province: areaIds[0],
          city: areaIds[1]
        })
      }
    }
    Picker.init(payload)
    Picker.show()
  }

  handleChangeText = (key) => (value) => {
    if (this.state[key] === value) return
    this.setState({ [key]: value })
  }

  handMade = () => {
    Layer.showLoading()
    this.props.cardManager.makeSurePlan({
      plan_id: this.state.data.plan.id,
      token: this.props.userAuth.token
    }).then(function (res) {
      Layer.hiddenLoading()
      Layer.showMsg('制定计划成功')
      navigationhelper.navigate('MakePlanSuccessView', {
        reserve_amount: res.data.reserve_amount,
        bank_name: res.data.bank_name,
        card_number: res.data.card_number
      })
    }).catch(function (error) {
      Layer.hiddenLoading()
      Layer.showMsg(error.message)
    })
  }

  handleNextStep = () => {
    if (this.state.data.auth == 1) {
      return this.handMade()
    } else {
      Layer.showLoading()
      //及时获取是否被更新了auth
      this.props.cardManager.authCard({
        token: this.props.userAuth.token,
        channel: this.state.data.plan.channel,
        bank_card_id: this.state.data.plan.user_bankcards_id
      }).then((res) => {
        console.log(res);
        Layer.hiddenLoading()
        if (res.data == 'BIND_CARD_AUTH') {
          return this.handMade()
        }else if(res.data.type == 'h5'){
          navigationhelper.navigate('Web', { url: res.data.page, title: '授权' })
        }else{
          navigationhelper.navigate('MakePlanCodeView', {
            plan: this.state.data.plan,
            channel_bankcard_id: res.data.channel_user_bankcard_id
          })
        }
      }).catch(function (error) {
        Layer.hiddenLoading()
        Layer.showMsg(error.message)
      })
    }
  }

  onUpdatePlan = (payload) => {
    var plan = this.state.data.plan
    Layer.showLoading()
    this.props.cardManager.updatePlan({
      token: this.props.userAuth.token,
      bankcard_id: plan.user_bankcards_id,
      repayment_money: plan.amount,
      channel: plan.channel,
      plan_day: plan.date_list,
      province: plan.province,
      city: plan.city,
      daily_repayment_times: plan.daily_repayment_times,
      plan_id: plan.id,
      ...payload
    }).then((res) => {
      Layer.hiddenLoading()
      if (res.status !== 'success') {
        return Layer.showLongMsg(res.failedMsg)
      }
      this.setState({
        data: res.data
      })
      console.log('update result is ', res)
    }).catch(function (error) {
      Layer.hiddenLoading()
      Layer.showMsg(error.message)
    })
  }

  renderGetVerifyCodeView = () => {
    let { isCountDown, countText, countColor } = this.state
    if (isCountDown) {
      return (
        <Text style={[styles.countDownStyle, { color: countColor }]}>
          {countText}
        </Text>
      )
    }
    return (
      <TouchableOpacity onPress={this.handleStartCountDownTimer}>
        <Text style={[styles.countDownStyle, { color: countColor }]}>
          {countText}
        </Text>
      </TouchableOpacity>
    )
  }

  renderCardInfoView = () => {
    var carNum = this.state.data.plan.card_number
    return (
      <View style={[styles.contentContainer, styles.hContainer, {
        justifyContent: 'center', minHeight: 60
      }]}>
        <Image source={{ uri: this.state.data.plan.bank_logo }} style={styles.icon} />
        <Text style={styles.name}>
          {this.state.data.plan.bank_name + '(' + carNum + ')'}
        </Text>
      </View>
    )
  }

  renderInfoView = () => {
    return (
      <View style={[styles.contentContainer, styles.infoContainer]}>
        <View style={styles.hContainer}>
          <Text style={styles.infoLabel}>{'还款金额'}</Text>
          <View style={{ flex: 1 }} />
          <Text style={styles.infoValue}>{'￥' + this.state.data.plan.amount}</Text>
        </View>
        <View style={{ height: 16 }} />
        <View style={styles.hContainer}>
          <Text style={styles.infoLabel}>{'还款手续费'}</Text>
          <View style={{ flex: 1 }} />
          <Text style={[styles.infoValue, {
            color: '#ff5b5b'
          }]}>
            {
              this.state.data.vip.vip === 0
                ?
                '-￥' + (parseFloat(this.state.data.plan.consume_fee) - parseFloat(this.state.data.vip.consume_fee)).toFixed(2)
                :
                ''
            }
          </Text>
          <View style={{ width: 10 }} />
          <Text style={styles.infoValue}>{'￥' + this.state.data.plan.consume_fee}</Text>
        </View>
        <View style={{ height: 16 }} />
        <View style={styles.hContainer}>
          <Text style={styles.infoLabel}>{'还款次数费'}</Text>
          <View style={{ flex: 1 }} />
          <Text style={styles.infoValue}>{'￥' + this.state.data.plan.repayment_fee}</Text>
        </View>
        <View style={{ height: 16 }} />
        <View style={styles.hContainer}>
          <View style={{ flex: 1 }} />
          <Text style={styles.infoLabel}>{'还款总手续费共计：'}</Text>
          <Text style={styles.infoValue}>{'￥'}</Text>
          <Text style={[styles.infoValue, {
            fontSize: 18
          }]}>{(parseFloat(this.state.data.plan.consume_fee) + parseFloat(this.state.data.plan.repayment_fee)).toFixed(2)}</Text>
        </View>
        {/* {
          this.state.data.vip.vip === 0
            ?
            <View style={[styles.hContainer, styles.mt16]} >
              <View style={{ flex: 1 }} />
              <Text style={styles.infoLabel}>升级VIP后还款总手续费共计:</Text>
              <Text style={styles.infoValue}>￥{(parseFloat(this.state.data.vip.consume_fee) + parseFloat(this.state.data.plan.repayment_fee)).toFixed(2)}</Text>
            </View>
            :
            <Text></Text>
        } */}

      </View>
    )
  }

  renderMemberView = () => {
    return (
      <TouchableOpacity style={[styles.contentContainer, styles.hContainer,
      styles.memberContainer]}>
        <View style={{ justifyContent: 'center' }}>
          <Text style={styles.memberTitle}>
            {'当前未想用会员优惠价'}
          </Text>
          <View style={{ height: 2 }} />
          <Text style={styles.memberTip}>
            {'开通会员可享受费率优惠'}
          </Text>
        </View>
        <View style={{ flex: 1 }} />
        <Image source={require('src/assets/icon_member.png')} />
        <View style={{ width: 6 }} />
        <Text style={styles.memberText}>
          {'开通会员'}
        </Text>
        <View style={{ width: 6 }} />
        <Image source={require('src/assets/icon_arrow_grey.png')} />
      </TouchableOpacity>
    )
  }

  renderPickerView = () => {
    let { area } = this.state
    return (
      <View style={styles.contentContainer}>
        <NameInput
          showLeftText
          editable={false}
          text={this.state.repaymentDate}
          leftText={'还款日期'}
          leftTextStyle={styles.leftTextStyle}
          placeholder={'请选择还款日期'}
          hideClearImage
          showRightImage
          rightImage={require('src/assets/icon_arrow_grey.png')}
          onPress={this.handleShowDatePicker} />
        <Divider style={{ marginLeft: 16, marginRight: 16 }} />
        <NameInput
          showLeftText
          editable={false}
          text={area[0] + ' ' + area[1]}
          leftText={'省市选择'}
          leftTextStyle={styles.leftTextStyle}
          placeholder={'请选择发卡行所在省市'}
          hideClearImage
          showRightImage
          rightImage={require('src/assets/icon_arrow_grey.png')}
          onPress={this.handleShowAreaPicker} />
        <Divider style={{ marginLeft: 16, marginRight: 16 }} />
        <NameInput
          showLeftText
          editable={false}
          leftText={'还款方式'}
          text={this.state.repaymentMethod}
          leftTextStyle={styles.leftTextStyle}
          placeholder={'请选择还款方式'}
          hideClearImage
          showRightImage
          rightImage={require('src/assets/icon_arrow_grey.png')}
          onPress={() => this.methodAction.show()} />
        <Divider style={{ marginLeft: 16, marginRight: 16 }} />
        <NameInput
          showLeftText
          editable={false}
          leftText={'还款通道'}
          text={this.state.repaymentChannel}
          leftTextStyle={styles.leftTextStyle}
          placeholder={'请选择还款通道'}
          hideClearImage
          showRightImage
          rightImage={require('src/assets/icon_arrow_grey.png')}
          onPress={() => this.channelAction.show()} />
      </View>
    )
  }

  renderMessageView = () => {
    return (
      <View style={[styles.messageContainer, styles.hContainer]}>
        <Image style={styles.mesageIcon}
          source={require('src/assets/icon_message.png')} />
        <View style={{ width: 8 }} />
        <Text style={styles.messageText}>
          {'您需要预留额度'}
          <Text style={{ color: '#ff2121' }}>{'￥'}</Text>
          <Text style={{ color: '#ff2121', fontSize: 18 }}>
            {this.state.data.plan.reserve_amount}
          </Text>
          {/*<Text style={{ color: '#378efb' }}>{'.00'}</Text>*/}
        </Text>
      </View>
    )
  }

  render() {
    let channel = this.state.data.channel || []
    channel = channel.slice(0)
    channel.push({ show_name: '取消' })
    let method = this.state.data.repayment_type || []
    method = method.slice(0)
    method.push({ name: '取消' })
    return (
      <KeyboardAvoidingView
        style={styles.container}
        behavior={Platform.OS === 'ios' ? 'padding' : 'none'}>
        <NavBar
          back={() => { navigationhelper.goBack() }}
          pressRight={() => {
            navigationhelper.navigate('MakePlanPreviewList', {
              detail: this.state.data.plan.detail
            })
          }}
          title={"计划明细"}
          titleColor={'#000'}
          barStyle={'dark-content'}
          right={<Text style={{ fontSize: 16, color: '#ff2121', fontFamily: 'PingFang SC' }}>预览</Text>}
        />
        <ScrollView
          bounces={false}
          showsVerticalScrollIndicator={false}
          keyboardShouldPersistTaps={'handled'}>
          <View style={{ height: 16 }} />
          {this.renderCardInfoView()}
          <View style={{ height: 12 }} />
          {this.renderInfoView()}
          <View style={{ height: 12 }} />
          {/* {
            this.state.data.vip.vip === 0
              ?
              this.renderMemberView()
              :
              null
          } */}
          {this.renderPickerView()}
          <View style={{ height: 12 }} />
          {this.renderMessageView()}
          <View style={{ height: 30 }} />
          <TouchableOpacity
            style={styles.addBtnContainer}
            onPress={this.handleNextStep}>
            <Text style={styles.addBtnText}>{'下一步'}</Text>
          </TouchableOpacity>
          <View style={{ height: 16 }} />
        </ScrollView>
        <ActionSheet
          ref={o => this.methodAction = o}
          cancelButtonIndex={method.length - 1}
          options={method.map((item) => { return item.name })}
          onPress={(index) => {
            if (index === method.length - 1) {
              return
            }
            this.setState({
              repaymentMethod: method[index].name
            })

            this.onUpdatePlan({
              daily_repayment_times: method[index].value
            })

          }} />
        <ActionSheet
          ref={o => this.channelAction = o}
          cancelButtonIndex={channel.length - 1}
          options={channel.map((item) => { return item.show_name })}
          onPress={(index) => {
            if (index === channel.length - 1) {
              return
            }
            this.setState({
              repaymentChannel: channel[index].show_name
            })
            this.onUpdatePlan({
              channel: channel[index].id
            })
          }} />
      </KeyboardAvoidingView>
    )
  }

}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5'
  },
  hContainer: {
    flexDirection: 'row',
    alignItems: 'center'
  },
  contentContainer: {
    backgroundColor: 'white'
  },
  icon: {
    width: 28,
    height: 28,
    borderRadius: 14,
    resizeMode: 'contain',
    backgroundColor: '#f5f5f5'
  },
  mt16: {
    marginTop: 16
  },
  name: {
    fontSize: 16,
    color: '#2e2e2e',
    fontWeight: 'bold',
    marginLeft: 12
  },
  infoContainer: {
    paddingTop: 15,
    paddingBottom: 15,
    paddingLeft: 16,
    paddingRight: 16
  },
  infoLabel: {
    fontSize: 12,
    color: '#8e8e93'
  },
  infoValue: {
    fontSize: 12,
    color: '#2e2e2e'
  },
  memberContainer: {
    height: 60,
    paddingLeft: 16,
    paddingRight: 16,
    marginBottom: 10
  },
  memberTitle: {
    fontSize: 15,
    color: '#2e2e2e'
  },
  memberTip: {
    fontSize: 11,
    color: '#8e8e93',
  },
  memberText: {
    fontSize: 15,
    color: '#378efb'
  },
  leftTextStyle: {
    width: 70,
    marginLeft: 16
  },
  countDownStyle: {
    paddingLeft: 16,
    paddingRight: 16,
    fontSize: 15
  },
  messageContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    minHeight: 35,
    paddingLeft: 13,
    paddingRight: 16,
    paddingTop: 9,
    paddingBottom: 9,
    marginLeft: 16,
    marginRight: 16,
    borderRadius: 5,
    backgroundColor: 'white'
  },
  messageIcon: {
    width: 18,
    height: 18,
    borderRadius: 9,
    marginRight: 8,
    resizeMode: 'contain'
  },
  messageText: {
    fontSize: 12,
    color: '#8e8e93',
  },
  addBtnContainer: {
    height: 50,
    marginLeft: 16,
    marginRight: 16,
    borderRadius: 5,
    backgroundColor: '#ff2121',
    alignItems: 'center',
    justifyContent: 'center'
  },
  addBtnText: {
    fontSize: 16,
    color: 'white',
    fontWeight: 'bold'
  }
})